package com.surfilter.geet.code;

import com.surfilter.geet.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

public class GeetestImage {

    private static final Logger logger = LoggerFactory.getLogger(GeetestImage.class);
    private static String gee_screen_img_path = ResourceBundle.getBundle("collect-config").getString("gee_screen_img_path");
    private static int[][] imgArray;

    static {
        imgArray = new int[52][2];
        imgArray[0][0] = 157;
        imgArray[0][1] = 58;
        imgArray[1][0] = 145;
        imgArray[1][1] = 58;
        imgArray[2][0] = 265;
        imgArray[2][1] = 58;
        imgArray[3][0] = 277;
        imgArray[3][1] = 58;
        imgArray[4][0] = 181;
        imgArray[4][1] = 58;
        imgArray[5][0] = 169;
        imgArray[5][1] = 58;
        imgArray[6][0] = 241;
        imgArray[6][1] = 58;
        imgArray[7][0] = 253;
        imgArray[7][1] = 58;
        imgArray[8][0] = 109;
        imgArray[8][1] = 58;
        imgArray[9][0] = 97;
        imgArray[9][1] = 58;
        imgArray[10][0] = 289;
        imgArray[10][1] = 58;
        imgArray[11][0] = 301;
        imgArray[11][1] = 58;
        imgArray[12][0] = 85;
        imgArray[12][1] = 58;
        imgArray[13][0] = 73;
        imgArray[13][1] = 58;
        imgArray[14][0] = 25;
        imgArray[14][1] = 58;
        imgArray[15][0] = 37;
        imgArray[15][1] = 58;
        imgArray[16][0] = 13;
        imgArray[16][1] = 58;
        imgArray[17][0] = 1;
        imgArray[17][1] = 58;
        imgArray[18][0] = 121;
        imgArray[18][1] = 58;
        imgArray[19][0] = 133;
        imgArray[19][1] = 58;
        imgArray[20][0] = 61;
        imgArray[20][1] = 58;
        imgArray[21][0] = 49;
        imgArray[21][1] = 58;
        imgArray[22][0] = 217;
        imgArray[22][1] = 58;
        imgArray[23][0] = 229;
        imgArray[23][1] = 58;
        imgArray[24][0] = 205;
        imgArray[24][1] = 58;
        imgArray[25][0] = 193;
        imgArray[25][1] = 58;
        imgArray[26][0] = 145;
        imgArray[26][1] = 0;
        imgArray[27][0] = 157;
        imgArray[27][1] = 0;
        imgArray[28][0] = 277;
        imgArray[28][1] = 0;
        imgArray[29][0] = 265;
        imgArray[29][1] = 0;
        imgArray[30][0] = 169;
        imgArray[30][1] = 0;
        imgArray[31][0] = 181;
        imgArray[31][1] = 0;
        imgArray[32][0] = 253;
        imgArray[32][1] = 0;
        imgArray[33][0] = 241;
        imgArray[33][1] = 0;
        imgArray[34][0] = 97;
        imgArray[34][1] = 0;
        imgArray[35][0] = 109;
        imgArray[35][1] = 0;
        imgArray[36][0] = 301;
        imgArray[36][1] = 0;
        imgArray[37][0] = 289;
        imgArray[37][1] = 0;
        imgArray[38][0] = 73;
        imgArray[38][1] = 0;
        imgArray[39][0] = 85;
        imgArray[39][1] = 0;
        imgArray[40][0] = 37;
        imgArray[40][1] = 0;
        imgArray[41][0] = 25;
        imgArray[41][1] = 0;
        imgArray[42][0] = 1;
        imgArray[42][1] = 0;
        imgArray[43][0] = 13;
        imgArray[43][1] = 0;
        imgArray[44][0] = 133;
        imgArray[44][1] = 0;
        imgArray[45][0] = 121;
        imgArray[45][1] = 0;
        imgArray[46][0] = 49;
        imgArray[46][1] = 0;
        imgArray[47][0] = 61;
        imgArray[47][1] = 0;
        imgArray[48][0] = 229;
        imgArray[48][1] = 0;
        imgArray[49][0] = 217;
        imgArray[49][1] = 0;
        imgArray[50][0] = 193;
        imgArray[50][1] = 0;
        imgArray[51][0] = 205;
        imgArray[51][1] = 0;
    }

    public static void imageTest() throws IOException {
        File file = new File(gee_screen_img_path);
        if (!file.exists()) {
            file.mkdirs();
        }
        BufferedImage bi = ImageIO.read(new File(gee_screen_img_path + "save.jpg"));
        BufferedImage bi1 = ImageIO.read(new File(gee_screen_img_path + "save1.jpg"));

        //获取图像的宽度和高度
        int width = bi.getWidth();
        int height = bi.getHeight();

        int width1 = bi1.getWidth();
        int height1 = bi1.getHeight();
        System.out.println("两张图片不具有可比性" + "w:" + width + "/" + width1 + " l" + height + "/" + height1);
        if (width != width1 || height != height1) {
            return;
        }
        Set<Integer> sets = new HashSet<Integer>();
        //扫描图片
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {//行扫描
                int dip = bi.getRGB(j, i);
                int dip1 = bi1.getRGB(j, i);
                if (dip != dip1) {
                    int legt = Math.abs(Math.abs(dip1) - Math.abs(dip));
                    if (legt > 4000000) {
                        System.out.println(dip + "++" + dip1 + "++" + legt);
                        sets.add(j);
                    }
                }
//                if(j == 133 && i == 76){
//                	System.out.println(dip + "+++" + dip1 + "+++" + Math.abs(dip1 - dip));
//                }
            }
        }
        System.out.println(sets.size());
        int sum = 0;
        for (Integer num : sets) {
            sum += num;
        }
        System.out.println(sum / sets.size());
    }

    public static int  getMoveLength(String imageUrl1, String imageUrl2, String uuid) throws MalformedURLException, IOException {
        int length = 0;
        byte[] bat1 = HttpUtil.getRomoteUrl(imageUrl1);
        byte[] bat2 = HttpUtil.getRomoteUrl(imageUrl2);

        File file = new File(gee_screen_img_path +"/"+uuid+"/");
        if (!file.exists()) {
            file.mkdirs();
        }

        BufferedImage imageBuf1 = ImageIO.read(new ByteArrayInputStream(bat1));
        BufferedImage imageBuf2 = ImageIO.read(new ByteArrayInputStream(bat2));
        imageBuf1 = getGeetestImg(imageBuf1, imgArray);
        imageBuf2 = getGeetestImg(imageBuf2, imgArray);
        ImageIO.write(imageBuf1, "jpg", new File(gee_screen_img_path +"/"+uuid+"/"+ "save.jpg"));
        ImageIO.write(imageBuf2, "jpg", new File(gee_screen_img_path +"/"+uuid+"/"+ "save1.jpg"));

        if (imageBuf1 == null || imageBuf2 == null) return 0;

        int width = imageBuf1.getWidth();
        int height = imageBuf1.getHeight();
        int width1 = imageBuf2.getWidth();
        int height1 = imageBuf2.getHeight();
        if (width != width1 || height != height1) {
            System.out.println("两张图片不具有可比性" + "w:" + width + "/" + width1 + " l" + height + "/" + height1);
            return length;
        }
//		Set<Integer> sets = new HashSet<Integer>();
        int minp = 0, maxp = 0;
        for (int i = 0; i < height; i++) {
            int minptemp = 0, maxptemp = 0;
            for (int j = 0; j < width; j++) {//行扫描
                int dip = imageBuf1.getRGB(j, i);
                int dip1 = imageBuf2.getRGB(j, i);
                if (dip != dip1) {
                    int legt = Math.abs(Math.abs(dip1) - Math.abs(dip));
                    if (legt > 2500000) {
                        imageBuf1.setRGB(j, i, 0);
//                		sets.add(j);
                        if (minptemp == 0) {
                            minptemp = j;
                            maxptemp = j;
                        } else if (j > maxptemp) {
                            maxptemp = j;
                        }
                    }
                }
            }
            if (Math.abs(maxptemp - minptemp - 44) < Math.abs(maxp - minp - 44)) {
                maxp = maxptemp;
                minp = minptemp;
            }
        }
        ImageIO.write(imageBuf1, "jpg", new File(gee_screen_img_path +"/"+uuid+"/"+ "deal.jpg"));
        length = (maxp + minp) / 2;
        return length;
    }

    /**
     * 合成指定的多张图片到一张图片
     *
     * @param imgSrcList       图片的地址列表
     * @param topLeftPointList 每张小图片的偏移量
     * @param countOfLine      每行的小图片个数
     * @param cutWidth         每张小图片截取的宽度（像素）
     * @param cutHeight        每张小图片截取的高度（像素）
     * @param savePath         合并后图片的保存路径
     * @param subfix           合并后图片的后缀
     * @return 是否合并成功
     */
    public static boolean combineImages(List<String> imgSrcList, List<String[]> topLeftPointList, int countOfLine, int cutWidth, int cutHeight, String savePath, String subfix) {
        if (imgSrcList == null || savePath == null || savePath.trim().length() == 0) return false;
        BufferedImage lastImage = new BufferedImage(cutWidth * countOfLine, cutHeight * ((int) (Math.floor(imgSrcList.size() / countOfLine))), BufferedImage.TYPE_INT_RGB);
        String prevSrc = "";
        BufferedImage prevImage = null;
        try {
            for (int i = 0; i < imgSrcList.size(); i++) {
                String src = imgSrcList.get(i);
                BufferedImage image;
                if (src.equals(prevSrc)) image = prevImage;
                else {
                    if (src.trim().toLowerCase().startsWith("http"))
                        image = ImageIO.read(new URL(src));
                    else
                        image = ImageIO.read(new File(src));
                    prevSrc = src;
                    prevImage = image;

                }
                if (image == null) continue;
                String[] topLeftPoint = topLeftPointList.get(i);
                int[] pixArray = image.getRGB(0 - Integer.parseInt(topLeftPoint[0].trim()), 0 - Integer.parseInt(topLeftPoint[1].trim()), cutWidth, cutHeight, null, 0, cutWidth);
                int startX = ((i) % countOfLine) * cutWidth;
                int startY = ((i) / countOfLine) * cutHeight;
                lastImage.setRGB(startX, startY, cutWidth, cutHeight, pixArray, 0, cutWidth);
            }
            File file = new File(savePath);
            return ImageIO.write(lastImage, subfix, file);
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    public static BufferedImage getGeetestImg(BufferedImage img, int[][] imgArray) throws IOException {
//        BufferedImage img = ImageIO.read(new ByteArrayInputStream(binary));
        List<BufferedImage> list = new ArrayList<BufferedImage>();
        for (int[] anImgArray : imgArray) {
            BufferedImage subimage = img.getSubimage(anImgArray[0], anImgArray[1], 10, 58);
            list.add(subimage);
//            ImageIO.write(subimage, "jpg", new File("d:\\image\\imgs"+i+".jpg"));
        }
        BufferedImage mergeImageUp = null;
        BufferedImage mergeImageDown = null;
        int mid = list.size() >>> 1;
        for (int i = 0; i < mid - 1; i++) {
            mergeImageUp = mergeImage(mergeImageUp == null ? list.get(i) : mergeImageUp, list.get(i + 1), true);
        }
        for (int i = mid; i < list.size() - 1; i++) {
            mergeImageDown = mergeImage(mergeImageDown == null ? list.get(i) : mergeImageDown, list.get(i + 1), true);
        }
        img = mergeImage(mergeImageUp, mergeImageDown, false);
        return img;
    }

    public static BufferedImage mergeImage(BufferedImage img1,
                                           BufferedImage img2, boolean isHorizontal) throws IOException {
        int w1 = img1.getWidth();
        int h1 = img1.getHeight();
        int w2 = img2.getWidth();
        int h2 = img2.getHeight();
        // 从图片中读取RGB
        int[] ImageArrayOne = new int[w1 * h1];
        ImageArrayOne = img1.getRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 逐行扫描图像中各个像素的RGB到数组中
        int[] ImageArrayTwo = new int[w2 * h2];
        ImageArrayTwo = img2.getRGB(0, 0, w2, h2, ImageArrayTwo, 0, w2);

        // 生成新图片
        BufferedImage DestImage = null;
        if (isHorizontal) { // 水平方向合并
            DestImage = new BufferedImage(w1 + w2, h1, BufferedImage.TYPE_INT_RGB);
            DestImage.setRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB
            DestImage.setRGB(w1, 0, w2, h2, ImageArrayTwo, 0, w2);
        } else { // 垂直方向合并
            DestImage = new BufferedImage(w1, h1 + h2,
                    BufferedImage.TYPE_INT_RGB);
            DestImage.setRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB
            DestImage.setRGB(0, h1, w2, h2, ImageArrayTwo, 0, w2); // 设置下半部分的RGB
        }
        return DestImage;
    }

}
